package com.voodoo.androidserialport;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import com.voodoo.serialPort.SerialPortHelper;
import com.voodoo.serialPort.entity.BAUDRATE;
import com.voodoo.serialPort.entity.DATAB;
import com.voodoo.serialPort.entity.Device;
import com.voodoo.serialPort.entity.PARITY;
import com.voodoo.serialPort.entity.STOPB;
import com.voodoo.serialPort.listener.IOpenSerialPortListener;
import com.voodoo.serialPort.listener.ISerialPortDataListener;
import com.voodoo.serialPort.listener.Status;

import java.io.File;
import java.util.Arrays;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    SerialPortHelper serialPortHelper;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (serialPortHelper == null) {
            serialPortHelper = new SerialPortHelper();
        }
        String[] allDeicesPath = serialPortHelper.getAllDeicesPath();
        Log.i(TAG, "onCreate: 获取到的串口名称列表：" + Arrays.toString(allDeicesPath));

        serialPortHelper.setPort("/dev/ttyS4");
        serialPortHelper.setBaudRate(BAUDRATE.getBaudrate(BAUDRATE.B9600));
        serialPortHelper.setStopBits(STOPB.getStopBit(STOPB.B1));
        serialPortHelper.setDataBits(DATAB.getDataBit(DATAB.CS8));
        serialPortHelper.setParity(PARITY.getParity(PARITY.NONE));

        serialPortHelper.setIOpenSerialPortListener(new IOpenSerialPortListener() {
            @Override
            public void onSuccess(File device) {
                Log.i(TAG, "onSuccess: 打开成功，串口：" + device.getName());
            }

            @Override
            public void onFail(File device, Status status) {
                Log.i(TAG, "onFail: 打开失败，原因：" + status);
            }
        });
        serialPortHelper.setISerialPortDataListener(new ISerialPortDataListener() {
            @Override
            public void onDataReceived(byte[] bytes) {
                Log.i(TAG, "onDataReceived: 接收数据：" + Arrays.toString(bytes));
            }

            @Override
            public void onDataSend(byte[] bytes) {
                Log.i(TAG, "onDataSend: 发送数据：" + Arrays.toString(bytes));
            }
        });
        serialPortHelper.open();

    }

    public void sendBytes(View view) {
        serialPortHelper.sendBytes(new byte[]{0x10, 0x06, 0x00, 0x01, 0x00, 0x01, 0x00, 0x18});
    }

}